// 基础信息管理模块
const BaseInfoModule = {
    currentDeptPage: 1,
    currentTeacherPage: 1,
    currentPositionPage: 1,
    currentTeacherPositionPage: 1,
    pageSize: 10,
    positionOptions: [], // 存储岗位选项数据

    // 初始化
    init() {
        console.log('基础信息管理模块初始化');
        // 加载部门下拉框数据
        this.loadDeptOptions();
        // 加载岗位下拉框数据
        this.loadPositionOptions();
    },

    // 加载部门下拉框数据
    loadDeptOptions() {
        CommonModule.apiRequest('/dept/options')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data) {
                    this.populateDeptSelect(data.data);
                } else {
                    console.error('加载部门选项失败:', data.message);
                }
            })
            .catch(error => {
                console.error('加载部门选项失败:', error);
            });
    },

    // 填充部门下拉框
    populateDeptSelect(depts) {
        // 教师信息管理页面的部门下拉框
        const teacherDeptSelect = document.getElementById('teacherDeptSearch');
        if (teacherDeptSelect) {
            // 清空现有选项（保留"全部部门"选项）
            teacherDeptSelect.innerHTML = '<option value="">全部部门</option>';
            
            // 添加部门选项
            depts.forEach(dept => {
                const option = document.createElement('option');
                option.value = dept.bmbh;
                option.textContent = dept.bmmc;
                teacherDeptSelect.appendChild(option);
            });
        }

        // 教师岗位管理页面的部门下拉框
        const tpDeptSelect = document.getElementById('tpDeptSearch');
        if (tpDeptSelect) {
            // 清空现有选项（保留"全部部门"选项）
            tpDeptSelect.innerHTML = '<option value="">全部部门</option>';
            
            // 添加部门选项
            depts.forEach(dept => {
                const option = document.createElement('option');
                option.value = dept.bmbh;
                option.textContent = dept.bmmc;
                tpDeptSelect.appendChild(option);
            });
        }
    },

    // 加载岗位下拉框数据
    loadPositionOptions() {
        CommonModule.apiRequest('/position/type/options')
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data) {
                    this.positionOptions = data.data; // 存储岗位数据
                    this.populatePositionSelect(data.data);
                } else {
                    console.error('加载岗位选项失败:', data.message);
                }
            })
            .catch(error => {
                console.error('加载岗位选项失败:', error);
            });
    },

    // 根据岗位编号获取岗位名称
    getPositionNameByCode(gwbh) {
        if (!gwbh || !this.positionOptions) return gwbh || '';
        const position = this.positionOptions.find(pos => pos.gwbh === gwbh);
        return position ? position.gwmc : gwbh;
    },

    // 填充岗位下拉框
    populatePositionSelect(positions) {
        // 教师信息管理页面的岗位下拉框
        const teacherPositionSelect = document.getElementById('teacherPositionSearch');
        if (teacherPositionSelect) {
            // 清空现有选项（保留"全部岗位"选项）
            teacherPositionSelect.innerHTML = '<option value="">全部岗位</option>';
            
            // 添加岗位选项
            positions.forEach(position => {
                const option = document.createElement('option');
                option.value = position.gwbh;
                option.textContent = position.gwmc;
                teacherPositionSelect.appendChild(option);
            });
        }

        // 教师岗位管理页面的岗位下拉框
        const tpPositionSelect = document.getElementById('tpPositionSearch');
        if (tpPositionSelect) {
            // 清空现有选项（保留"全部岗位"选项）
            tpPositionSelect.innerHTML = '<option value="">全部岗位</option>';
            
            // 添加岗位选项
            positions.forEach(position => {
                const option = document.createElement('option');
                option.value = position.gwbh;
                option.textContent = position.gwmc;
                tpPositionSelect.appendChild(option);
            });
        }
    },

    // ========== 部门管理 ==========
    loadDeptList(page = 1) {
        this.currentDeptPage = page;
        
        const params = new URLSearchParams({
            page: page,
            size: this.pageSize
        });

        const bmmc = document.getElementById('deptNameSearch')?.value || '';
        const bmlx = document.getElementById('deptTypeSearch')?.value || '';
        if (bmmc) params.append('bmmc', bmmc);
        if (bmlx) params.append('bmlx', bmlx);

        CommonModule.apiRequest(`/dept/list?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.renderDeptTable(data.data.records || []);
                    if (data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / this.pageSize);
                        CommonModule.createPagination('deptPagination', totalPages, page, (p) => this.loadDeptList(p));
                    }
                } else {
                    CommonModule.handleApiError(new Error(data.message), '加载部门列表');
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载部门列表');
            });
    },

    renderDeptTable(depts) {
        const tbody = document.querySelector('#deptTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (depts && depts.length > 0) {
            depts.forEach(dept => {
                const deptTypeText = this.getDeptTypeText(dept.bmlx);
                const statusText = dept.bmzt === '0' ? '正常' : '停用';

                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${dept.bmbh || ''}</td>
                    <td>${dept.bmmc || ''}</td>
                    <td>${deptTypeText}</td>
                    <td>${statusText}</td>
                    <td>
                        <button class="btn btn-primary btn-small" onclick="BaseInfoModule.editDept('${dept.bmbh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="BaseInfoModule.deleteDept('${dept.bmbh}')">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="5">暂无数据</td></tr>';
        }
    },

    getDeptTypeText(bmlx) {
        const typeMap = {
            '0': '职能部门',
            '1': '二级学院',
            '2': '社区',
            '3': '其他'
        };
        return typeMap[bmlx] || '未知';
    },

    showDeptModal(deptData = null) {
        const isEdit = deptData !== null;
        const title = isEdit ? '编辑部门' : '新增部门';

        const content = `
            <form id="deptForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">部门编号</label>
                        <input type="text" name="bmbh" class="form-input"
                               value="${isEdit ? deptData.bmbh : ''}"
                               ${isEdit ? 'readonly' : ''} placeholder="请输入部门编号" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">部门名称</label>
                        <input type="text" name="bmmc" class="form-input"
                               value="${isEdit ? deptData.bmmc : ''}" placeholder="请输入部门名称" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">部门类型</label>
                        <select name="bmlx" class="form-input" required>
                            <option value="">请选择</option>
                            <option value="0" ${isEdit && deptData.bmlx === '0' ? 'selected' : ''}>职能部门</option>
                            <option value="1" ${isEdit && deptData.bmlx === '1' ? 'selected' : ''}>二级学院</option>
                            <option value="2" ${isEdit && deptData.bmlx === '2' ? 'selected' : ''}>社区</option>
                            <option value="3" ${isEdit && deptData.bmlx === '3' ? 'selected' : ''}>其他</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">状态</label>
                        <select name="bmzt" class="form-input" required>
                            <option value="0" ${!isEdit || deptData.bmzt === '0' ? 'selected' : ''}>正常</option>
                            <option value="1" ${isEdit && deptData.bmzt === '1' ? 'selected' : ''}>停用</option>
                        </select>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="BaseInfoModule.saveDept(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = deptData;
    },

    saveDept(isEdit) {
        const form = document.getElementById('deptForm');
        const formData = new FormData(form);
        const deptData = Object.fromEntries(formData);

        if (!deptData.bmbh || !deptData.bmmc || !deptData.bmlx || !deptData.bmzt) {
            alert('请填写所有必填字段');
            return;
        }

        const url = isEdit ? `/dept/${deptData.bmbh}` : '/dept';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(deptData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadDeptList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${data.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存部门');
        });
    },

    editDept(bmbh) {
        CommonModule.apiRequest(`/dept/${bmbh}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showDeptModal(data.data);
                } else {
                    alert('获取部门信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取部门详情');
            });
    },

    deleteDept(bmbh) {
        if (!CommonModule.confirmAction('确认删除该部门？删除后不可恢复。')) {
            return;
        }

        CommonModule.apiRequest(`/dept/${bmbh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                CommonModule.showSuccess('删除成功');
                this.loadDeptList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除部门');
        });
    },

    searchDept() {
        this.loadDeptList(1);
    },

    importDept() {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.xlsx,.xls';
        fileInput.onchange = (event) => {
            const file = event.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            fetch(CommonModule.globalConfig.apiBase + '/dept/import', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    CommonModule.showSuccess('导入成功：' + data.message);
                    this.loadDeptList();
                } else {
                    alert('导入失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '导入');
            });
        };

        fileInput.click();
    },

    // 下载部门导入模板
    downloadDeptTemplate() {
        window.open(CommonModule.globalConfig.apiBase + '/dept/template/download', '_blank');
    },

    // ========== 教师管理 ==========
    loadTeacherList(page = 1) {
        this.currentTeacherPage = page;
        
        const params = new URLSearchParams({
            page: page,
            size: this.pageSize
        });

        const jsxm = document.getElementById('teacherNameSearch')?.value || '';
        const bmbh = document.getElementById('teacherDeptSearch')?.value || '';
        const jslx = document.getElementById('teacherTypeSearch')?.value || '';
        const gw = document.getElementById('teacherPositionSearch')?.value || '';
        if (jsxm) params.append('jsxm', jsxm);
        if (bmbh) params.append('bmbh', bmbh);
        if (jslx) params.append('jslx', jslx);
        if (gw) params.append('gw', gw);

        CommonModule.apiRequest(`/teacher/list?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.renderTeacherTable(data.data.records || []);
                    if (data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / this.pageSize);
                        CommonModule.createPagination('teacherPagination', totalPages, page, (p) => this.loadTeacherList(p));
                    }
                } else {
                    CommonModule.handleApiError(new Error(data.message), '加载教师列表');
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载教师列表');
            });
    },

    renderTeacherTable(teachers) {
        const tbody = document.querySelector('#teacherTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (teachers && teachers.length > 0) {
            teachers.forEach(teacher => {
                const typeText = teacher.jslx === '0' ? '行政' : '教师';
                const cpText = teacher.sfcp === '0' ? '参评' : '不参评';
                const statusText = teacher.jszt === '0' ? '正常' : '停用';
                const positionName = this.getPositionNameByCode(teacher.gw); // 获取岗位名称

                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${teacher.jsbh || ''}</td>
                    <td>${teacher.jsgh || ''}</td>
                    <td>${teacher.jsxm || ''}</td>
                    <td>${teacher.bmbh || ''}</td>
                    <td>${teacher.bmmc || ''}</td>
                    <td>${positionName}</td>
                    <td>${typeText}</td>
                    <td>${cpText}</td>
                    <td>${statusText}</td>
                    <td>
                        <button class="btn btn-primary btn-small" onclick="BaseInfoModule.editTeacher('${teacher.jsbh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="BaseInfoModule.deleteTeacher('${teacher.jsbh}')">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="10">暂无数据</td></tr>';
        }
    },

    searchTeacher() {
        this.loadTeacherList(1);
    },

    showTeacherModal(teacherData = null) {
        const isEdit = teacherData !== null;
        const title = isEdit ? '编辑教师' : '新增教师';

        const content = `
            <form id="teacherForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">教师编号</label>
                        <input type="text" name="jsbh" class="form-input"
                               value="${isEdit ? teacherData.jsbh : ''}"
                               ${isEdit ? 'readonly' : ''} placeholder="请输入教师编号" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">教师姓名</label>
                        <input type="text" name="jsxm" class="form-input"
                               value="${isEdit ? teacherData.jsxm : ''}" placeholder="请输入教师姓名" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">部门编号</label>
                        <input type="text" name="bmbh" class="form-input"
                               value="${isEdit ? teacherData.bmbh : ''}" placeholder="请输入部门编号" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">部门名称</label>
                        <input type="text" name="bmmc" class="form-input"
                               value="${isEdit ? teacherData.bmmc : ''}" placeholder="请输入部门名称" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">教师类型</label>
                        <select name="jslx" class="form-input" required>
                            <option value="">请选择</option>
                            <option value="0" ${isEdit && teacherData.jslx === '0' ? 'selected' : ''}>行政</option>
                            <option value="1" ${isEdit && teacherData.jslx === '1' ? 'selected' : ''}>教师</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">是否参评</label>
                        <select name="sfcp" class="form-input" required>
                            <option value="0" ${!isEdit || teacherData.sfcp === '0' ? 'selected' : ''}>参评</option>
                            <option value="1" ${isEdit && teacherData.sfcp === '1' ? 'selected' : ''}>不参评</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">岗位</label>
                        <select name="gw" id="teacherPositionSelect" class="form-input">
                            <option value="">请选择岗位</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">手机号码</label>
                        <input type="text" name="sjhm" class="form-input"
                               value="${isEdit ? teacherData.sjhm : ''}" placeholder="请输入手机号码">
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">状态</label>
                        <select name="jszt" class="form-input" required>
                            <option value="0" ${!isEdit || teacherData.jszt === '0' ? 'selected' : ''}>正常</option>
                            <option value="1" ${isEdit && teacherData.jszt === '1' ? 'selected' : ''}>停用</option>
                        </select>
                    </div>
                    <div class="form-group">
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="BaseInfoModule.saveTeacher(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = teacherData;
        
        // 填充岗位下拉框
        const positionSelect = document.getElementById('teacherPositionSelect');
        if (positionSelect && this.positionOptions) {
            // 清空现有选项（保留"请选择岗位"选项）
            positionSelect.innerHTML = '<option value="">请选择岗位</option>';
            
            // 添加岗位选项
            this.positionOptions.forEach(position => {
                const option = document.createElement('option');
                option.value = position.gwbh;
                option.textContent = position.gwmc;
                // 如果是编辑模式且当前教师的岗位匹配，则选中
                if (isEdit && teacherData.gw && teacherData.gw === position.gwbh) {
                    option.selected = true;
                }
                positionSelect.appendChild(option);
            });
        }
    },

    saveTeacher(isEdit) {
        const form = document.getElementById('teacherForm');
        const formData = new FormData(form);
        const teacherData = Object.fromEntries(formData);

        if (!teacherData.jsbh || !teacherData.jsxm || !teacherData.bmbh || !teacherData.bmmc ||
            !teacherData.jslx || !teacherData.sfcp || !teacherData.jszt) {
            alert('请填写所有必填字段');
            return;
        }

        const url = isEdit ? `/teacher/${teacherData.jsbh}` : '/teacher';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(teacherData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadTeacherList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${data.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存教师');
        });
    },

    editTeacher(jsbh) {
        CommonModule.apiRequest(`/teacher/${jsbh}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    this.showTeacherModal(data.data);
                } else {
                    alert('获取教师信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取教师详情');
            });
    },

    deleteTeacher(jsbh) {
        if (!CommonModule.confirmAction('确认删除该教师？删除后不可恢复。')) {
            return;
        }

        CommonModule.apiRequest(`/teacher/${jsbh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                CommonModule.showSuccess('删除成功');
                this.loadTeacherList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除教师');
        });
    },

    importTeacher() {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.xlsx,.xls';
        fileInput.onchange = (event) => {
            const file = event.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            fetch(CommonModule.globalConfig.apiBase + '/teacher/import', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    CommonModule.showSuccess('导入成功：' + data.message);
                    this.loadTeacherList();
                } else {
                    alert('导入失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '导入');
            });
        };

        fileInput.click();
    },

    // 下载教师导入模板
    downloadTeacherTemplate() {
        window.open(CommonModule.globalConfig.apiBase + '/teacher/template/download', '_blank');
    },

    // 提取教师数据
    extractTeacherData() {
        if (!confirm('确定要从企业微信和OA系统提取教师数据吗？此操作将更新教师的企业微信、手机号码和工号信息。')) {
            return;
        }

        // 显示加载状态
        const extractBtn = document.querySelector('button[onclick="BaseInfoModule.extractTeacherData()"]');
        const originalText = extractBtn.textContent;
        extractBtn.textContent = '提取中...';
        extractBtn.disabled = true;

        CommonModule.apiRequest('/teacher/extract-data', {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200 || data.success) {
                CommonModule.showSuccess('数据提取成功：' + (data.message || data.data || '已完成数据提取'));
                // 刷新教师列表
                this.loadTeacherList();
            } else {
                CommonModule.showError('数据提取失败：' + (data.message || '未知错误'));
            }
        })
        .catch(error => {
            console.error('提取教师数据失败:', error);
            CommonModule.showError('数据提取失败，请检查网络连接');
        })
        .finally(() => {
            // 恢复按钮状态
            extractBtn.textContent = originalText;
            extractBtn.disabled = false;
        });
    },

    // ========== 岗位类型管理 ==========
    loadPositionTypeList(page = 1) {
        this.currentPositionPage = page;
        
        const params = new URLSearchParams({
            page: page,
            size: this.pageSize
        });

        const gwmc = document.getElementById('positionNameSearch')?.value;
        if (gwmc) params.append('gwmc', gwmc);

        CommonModule.apiRequest(`/position/type/list?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    this.renderPositionTypeTable(data.data.records || []);
                    if (data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / this.pageSize);
                        CommonModule.createPagination('positionPagination', totalPages, page, (p) => this.loadPositionTypeList(p));
                    }
                } else {
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载岗位类型');
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载岗位类型');
            });
    },

    renderPositionTypeTable(data) {
        const tbody = document.querySelector('#positionTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (data && data.length > 0) {
            data.forEach(position => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${position.gwbh || ''}</td>
                    <td>${position.gwmc || ''}</td>
                    <td>${position.gwms || ''}</td>
                    <td>
                        <button class="btn btn-primary btn-small" onclick="BaseInfoModule.editPositionType('${position.gwbh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="BaseInfoModule.deletePositionType('${position.gwbh}')">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="4">暂无数据</td></tr>';
        }
    },

    showPositionTypeModal(data = null) {
        const isEdit = data !== null;
        const title = isEdit ? '编辑岗位类型' : '新增岗位类型';
        
        const content = `
            <form id="positionTypeForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">岗位编号</label>
                        <input type="text" name="gwbh" class="form-input" value="${isEdit ? data.gwbh : ''}" ${isEdit ? 'readonly' : ''} required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">岗位名称</label>
                        <input type="text" name="gwmc" class="form-input" value="${isEdit ? data.gwmc : ''}" required>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">岗位类型</label>
                        <select name="gwlx" class="form-input" required>
                            <option value="">请选择</option>
                            <option value="0" ${isEdit && data.gwlx === '0' ? 'selected' : ''}>管理岗</option>
                            <option value="1" ${isEdit && data.gwlx === '1' ? 'selected' : ''}>教师岗</option>
                            <option value="2" ${isEdit && data.gwlx === '2' ? 'selected' : ''}>服务岗</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="form-label">状态</label>
                        <select name="gwzt" class="form-input" required>
                            <option value="0" ${!isEdit || data.gwzt === '0' ? 'selected' : ''}>正常</option>
                            <option value="1" ${isEdit && data.gwzt === '1' ? 'selected' : ''}>停用</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group" style="width: 100%;">
                        <label class="form-label">岗位描述</label>
                        <textarea name="gwms" class="form-input" rows="3">${isEdit ? (data.gwms || '') : ''}</textarea>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="BaseInfoModule.savePositionType(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = data;
    },

    savePositionType(isEdit) {
        const form = document.getElementById('positionTypeForm');
        const formData = new FormData(form);
        
        const positionData = {
            gwbh: formData.get('gwbh'),
            gwmc: formData.get('gwmc'),
            gwlx: formData.get('gwlx'),
            gwms: formData.get('gwms'),
            gwzt: formData.get('gwzt')
        };

        const url = isEdit ?
            `/position/type/${window.currentEditData.gwbh}` :
            '/position/type';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(positionData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadPositionTypeList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${result.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存岗位类型');
        });
    },

    editPositionType(gwbh) {
        CommonModule.apiRequest(`/position/type/${gwbh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.showPositionTypeModal(data.data);
                } else {
                    alert('获取岗位类型信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取岗位类型详情');
            });
    },

    deletePositionType(gwbh) {
        if (!CommonModule.confirmAction('确认删除该岗位类型？删除后不可恢复。')) {
            return;
        }

        CommonModule.apiRequest(`/position/type/${gwbh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('删除成功');
                this.loadPositionTypeList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除岗位类型');
        });
    },

    // ========== 教师岗位管理 ==========
    loadTeacherPositionList(page = 1) {
        this.currentTeacherPositionPage = page;

        const params = new URLSearchParams();
        params.append('page', page);
        params.append('size', this.pageSize);

        const jsxm = document.getElementById('tpTeacherNameSearch')?.value;
        const gwbh = document.getElementById('tpPositionSearch')?.value;
        const bmbh = document.getElementById('tpDeptSearch')?.value;
        if (jsxm) params.append('jsxm', jsxm);
        if (gwbh) params.append('gwbh', gwbh);
        if (bmbh) params.append('bmbh', bmbh);

        CommonModule.apiRequest(`/position/teacher/list?${params}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200 && data.data) {
                    this.renderTeacherPositionTable(data.data.records || []);
                    if (data.data.total > 0) {
                        const totalPages = Math.ceil(data.data.total / this.pageSize);
                        CommonModule.createPagination('teacherPositionPagination', totalPages, page, (p) => this.loadTeacherPositionList(p));
                    }
                } else {
                    CommonModule.handleApiError(new Error(data.message || '加载失败'), '加载教师岗位');
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '加载教师岗位');
            });
    },

    renderTeacherPositionTable(data) {
        const tbody = document.querySelector('#teacherPositionTableContent table tbody');
        if (!tbody) return;

        tbody.innerHTML = '';
        if (data && data.length > 0) {
            data.forEach(tp => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${tp.jsbh || ''}</td>
                    <td>${tp.jsxm || ''}</td>
                    <td>${tp.gwbh || ''}</td>
                    <td>${tp.gwmc || ''}</td>
                    <td>${tp.bmmc || ''}</td>
                    <td>
                        <button class="btn btn-primary btn-small" onclick="BaseInfoModule.editTeacherPosition('${tp.jsbh}', '${tp.gwbh}', '${tp.bmbh}')">编辑</button>
                        <button class="btn btn-danger btn-small" onclick="BaseInfoModule.deleteTeacherPosition('${tp.jsbh}', '${tp.gwbh}', '${tp.bmbh}')">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        } else {
            tbody.innerHTML = '<tr><td colspan="6">暂无数据</td></tr>';
        }
    },

    showTeacherPositionModal(data = null) {
        const isEdit = data !== null;
        const title = isEdit ? '编辑教师岗位关系' : '新增教师岗位关系';
        
        const content = `
            <form id="teacherPositionForm">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">教师编号</label>
                        <input type="text" name="jsbh" class="form-input" value="${isEdit ? data.jsbh : ''}" ${isEdit ? 'readonly' : ''} required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">教师姓名</label>
                        <input type="text" name="jsxm" class="form-input" value="${isEdit ? data.jsxm : ''}" readonly>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">岗位编号</label>
                        <input type="text" name="gwbh" class="form-input" value="${isEdit ? data.gwbh : ''}" ${isEdit ? 'readonly' : ''} required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">岗位名称</label>
                        <input type="text" name="gwmc" class="form-input" value="${isEdit ? data.gwmc : ''}" readonly>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">部门编号</label>
                        <input type="text" name="bmbh" class="form-input" value="${isEdit ? data.bmbh : ''}" ${isEdit ? 'readonly' : ''} required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">部门名称</label>
                        <input type="text" name="bmmc" class="form-input" value="${isEdit ? data.bmmc : ''}" readonly>
                    </div>
                </div>
                <div style="text-align: right; margin-top: 20px;">
                    <button type="button" class="btn btn-secondary" onclick="CommonModule.closeModal()">取消</button>
                    <button type="button" class="btn btn-primary" onclick="BaseInfoModule.saveTeacherPosition(${isEdit})">${isEdit ? '更新' : '保存'}</button>
                </div>
            </form>
        `;
        
        CommonModule.showModal(title, content);
        window.currentEditData = data;
    },

    saveTeacherPosition(isEdit) {
        const form = document.getElementById('teacherPositionForm');
        const formData = new FormData(form);
        
        const teacherPositionData = {
            jsbh: formData.get('jsbh'),
            gwbh: formData.get('gwbh'),
            bmbh: formData.get('bmbh')
        };

        const url = isEdit ?
            `/position/teacher/${window.currentEditData.jsbh}/${window.currentEditData.gwbh}/${window.currentEditData.bmbh}` :
            '/position/teacher';
        const method = isEdit ? 'PUT' : 'POST';

        CommonModule.apiRequest(url, {
            method: method,
            body: JSON.stringify(teacherPositionData)
        })
        .then(response => response.json())
        .then(result => {
            if (result.code === 200) {
                CommonModule.showSuccess(isEdit ? '更新成功' : '添加成功');
                CommonModule.closeModal();
                this.loadTeacherPositionList();
            } else {
                alert(`${isEdit ? '更新' : '添加'}失败：${result.message}`);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '保存教师岗位关系');
        });
    },

    editTeacherPosition(jsbh, gwbh, bmbh) {
        CommonModule.apiRequest(`/position/teacher/${jsbh}/${gwbh}/${bmbh}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    this.showTeacherPositionModal(data.data);
                } else {
                    alert('获取教师岗位信息失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '获取教师岗位详情');
            });
    },

    deleteTeacherPosition(jsbh, gwbh, bmbh) {
        if (!CommonModule.confirmAction('确认删除该教师岗位关系？删除后不可恢复。')) {
            return;
        }

        CommonModule.apiRequest(`/position/teacher/${jsbh}/${gwbh}/${bmbh}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                CommonModule.showSuccess('删除成功');
                this.loadTeacherPositionList();
            } else {
                alert('删除失败：' + data.message);
            }
        })
        .catch(error => {
            CommonModule.handleApiError(error, '删除教师岗位关系');
        });
    },

    searchTeacherPosition() {
        this.loadTeacherPositionList(1);
    },

    importTeacherPosition() {
        const fileInput = document.createElement('input');
        fileInput.type = 'file';
        fileInput.accept = '.xlsx,.xls';
        fileInput.onchange = (event) => {
            const file = event.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            fetch(CommonModule.globalConfig.apiBase + '/position/teacher/import', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    CommonModule.showSuccess('导入成功：' + data.message);
                    this.loadTeacherPositionList();
                } else {
                    alert('导入失败：' + data.message);
                }
            })
            .catch(error => {
                CommonModule.handleApiError(error, '导入');
            });
        };

        fileInput.click();
    },

    // 下载教师岗位导入模板
    downloadTeacherPositionTemplate() {
        window.open(CommonModule.globalConfig.apiBase + '/position/teacher/template/download', '_blank');
    }
};

// 导出模块
window.BaseInfoModule = BaseInfoModule; 